package ru.spb.osll.myfit.server.parser;

import java.util.ArrayList;
import java.util.List;

import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.server.Converter;


public class PageParser {
  private IPageElementParser m_currentParser;
  private final PageElementParserFactory m_parserFactory;
  
  
  public PageParser(Converter converter){
    m_parserFactory = new PageElementParserFactory(converter);
    m_currentParser = m_parserFactory.getDefaultParser();
  }
 
  public List<PageElement> parsePage(List<String> lines){
    ArrayList<PageElement> elements = new ArrayList<PageElement>();
    for(String line: lines){
       parseLine(line, elements);
    }
    
    if(m_currentParser instanceof IAccumulatingParser){
      PageElement element = ((IAccumulatingParser) m_currentParser).reset();
      if(element != null){
        elements.add(element);
      }
    }
    return elements;
  }
  
  private void parseLine(String line, List<PageElement> elements){
    IPageElementParser parser = m_parserFactory.getParser(line);
    if(!parser.equals(m_currentParser) && m_currentParser instanceof IAccumulatingParser){
       PageElement el = ((IAccumulatingParser) m_currentParser).reset();
       if(el != null){
         elements.add(el);
       }
    }
    
    m_currentParser = parser;
    PageElement element = m_currentParser.parse(line);
    
    if(element != null){
      elements.add(element);
    }    
  }
}
